package com.zhkj.txg.module.login.ui

import android.text.TextUtils
import androidx.lifecycle.Observer
import com.zhkj.lib.base.ViewModelFragment
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.txg.R
import com.zhkj.txg.module.login.vm.BindMobileViewModel
import com.zhkj.txg.utils.TextWatcherWrapper
import kotlinx.android.synthetic.main.fragment_bind_mobile.*

class BindMobileFragment : ViewModelFragment<BindMobileViewModel>() {
    override fun setViewModel(): BindMobileViewModel = createViewModel(true)
    override val layoutResId: Int = R.layout.fragment_bind_mobile

    override fun initUI() {
        // 发送验证码按钮点击事件
        btnSendCode.setOnClickListener {
            val newAccount = etAccount.text.toString()
            if (TextUtils.equals(newAccount, viewModel.mobile2GetCode)) {
                viewModel.pageLiveData.value = true
            } else viewModel.sendCode(newAccount)
        }
        // 判断账号长度是否符合规定
        etAccount.addTextChangedListener(TextWatcherWrapper {
            btnSendCode.isEnabled = !TextUtils.isEmpty(it) && it!!.length == 11
        })
    }

    override fun initViewModel() {
        viewModel.sendCodeLiveData.observe(viewLifecycleOwner, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            // 显示输入验证码页面
            if (response.status == HttpResponseStatus.Status.SUCCESS) response.response?.let {
                if (!it.restart) viewModel.pageLiveData.value = true
            }
        })
    }
}